package com.admin.system.modules.system.rest;

import com.admin.common.constant.ExceptionConstant;
import com.admin.common.entity.BaseEntity;
import com.admin.common.exception.BadRequestException;
import com.admin.common.exception.EntityExistException;
import com.admin.common.utils.PageResult;
import com.admin.component.web.MultipartFileUtil;
import com.admin.core.dto.JobQueryDTO;
import com.admin.core.entity.SysJob;
import com.admin.core.entity.SysUserJob;
import com.admin.logging.annotation.Log;
import com.admin.logging.enums.OperateTypeEnum;
import com.admin.system.modules.system.service.JobService;
import com.admin.system.modules.system.service.UserJobService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author sq-lan
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：岗位管理")
@RequestMapping("/api/job")
public class JobController {

    private final JobService jobService;
    private final UserJobService userJobService;

    @ApiOperation("查询岗位")
    @GetMapping
    @PreAuthorize("@ss.check('job:list','user:list')")
    public ResponseEntity<PageResult<SysJob>> paging(JobQueryDTO dto) {
        return new ResponseEntity<>(jobService.paging(dto), HttpStatus.OK);
    }

    @Log(module = "岗位管理", operateType = OperateTypeEnum.ADD)
    @ApiOperation("新增岗位")
    @PostMapping
    @PreAuthorize("@ss.check('job:add')")
    public ResponseEntity<Object> add(@Validated @RequestBody SysJob entity) {
        if (entity.getId() != null) {
            throw new BadRequestException(ExceptionConstant.ERROR_PARAM);
        }
        if (jobService.count(Wrappers.<SysJob>lambdaQuery().eq(SysJob::getName, entity.getName())) > 0) {
            throw new EntityExistException("岗位名称", entity.getName());
        }
        jobService.save(entity);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log(module = "岗位管理", operateType = OperateTypeEnum.MODIFY)
    @ApiOperation("修改岗位")
    @PutMapping
    @PreAuthorize("@ss.check('job:edit')")
    public ResponseEntity<Object> modify(@Validated(BaseEntity.Update.class) @RequestBody SysJob entity) {
        boolean existName = jobService.count(Wrappers.<SysJob>lambdaQuery()
                .eq(SysJob::getName, entity.getName())
                .ne(SysJob::getId, entity.getId()))
                > 0;
        if (existName) {
            throw new EntityExistException("岗位名称", entity.getName());
        }
        jobService.updateById(entity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log(module = "岗位管理", operateType = OperateTypeEnum.REMOVE)
    @ApiOperation("删除岗位")
    @DeleteMapping
    @PreAuthorize("@ss.check('job:del')")
    public ResponseEntity<Object> remove(@RequestBody Set<Integer> ids) {
        // 验证是否被用户关联
        long count = userJobService.count(Wrappers.<SysUserJob>lambdaQuery().in(SysUserJob::getJobId, ids));
        if (count > 0) {
            throw new BadRequestException("所选的岗位中存在用户关联，请解除关联再试！");
        }
        jobService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("导出岗位数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@ss.check('job:list')")
    public void export(HttpServletResponse response, JobQueryDTO dto) throws IOException {
        List<SysJob> jobs = jobService.list(dto);
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysJob job : jobs) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("岗位名称", job.getName());
            map.put("岗位状态", job.getEnabled() ? "启用" : "停用");
            map.put("创建日期", job.getCreateTime());
            list.add(map);
        }
        MultipartFileUtil.downloadExcel(list, response);
    }
}
